//
//  ObserveTiming.swift
//  ObserveTiming
//
//  Created by JY_NEW on 2021/10/30.
//

import Foundation

public protocol ObserveTimingDelegate: AnyObject {
    func timeIsUp()
    func timeIsOver()
}
/// 订阅观察时间段
public struct ObserveTiming {
    public weak var delegate: ObserveTimingDelegate? {
        didSet {
            if self.isNow {
                oldValue?.timeIsOver()
                self.delegate?.timeIsUp()
            }
        }
    }
    /// 当前是否处在该时段
    private(set) public var isNow = false {
        didSet {
            if oldValue != self.isNow {
                if self.isNow {
                    self.delegate?.timeIsUp()
                }else{
                    self.delegate?.timeIsOver()
                }
            }
        }
    }
    /// 触发订阅时机
    public mutating func enter () {
        self.isNow = true
    }
    /// 触发取消订阅时机
    public mutating func exit() {
        self.isNow = false
    }
}
